import React, { Component } from "react";

class CommentInput extends Component {
  constructor() {
    super();
    this.state = {
      username: "",
      content: ""
    };
  }

  componentDidMount() {
    this.input.focus();
  }

  componentWillMount() {
    this._loadUsername();
  }

  handleChangeUserName(event) {
    this.setState({ username: event.target.value });
  }

  handleChangeComment(event) {
    this.setState({ content: event.target.value });
  }

  handleSubmit() {
    if (this.props.onSubmit) {
      const { username, content } = this.state;
      this.props.onSubmit({
        username,
        content,
        createdTime: +new Date()
      });
    }
    this.setState({ content: "" });
  }

  handleKeydown(event) {
    if (event.keyCode === 13) {
      this.handleSubmit();
    }
  }

  _saveUsername(username) {
    localStorage.setItem("username", username);
  }

  handleUsernameBlur(event) {
    this._saveUsername(event.target.value);
  }

  _loadUsername() {
    const username = localStorage.getItem("username");
    if (username) this.setState({ username });
  }

  handleDeleteComment(index) {
    const comments = this.state.comments;
    comments.splice(index, 1);
    this.setState({ comments });
    this._saveComments(comments);
  }

  render() {
    return (
      <div className="input">
        <div className="input-wrap">
          <span>用户：</span>
          <input
            ref={input => (this.input = input)}
            className="user"
            value={this.state.username}
            onChange={this.handleChangeUserName.bind(this)}
            onBlur={this.handleUsernameBlur.bind(this)}
          />
        </div>
        <div className="text-wrap">
          <span>评论：</span>
          <textarea
            className="comment"
            value={this.state.content}
            onChange={this.handleChangeComment.bind(this)}
            onKeyDown={this.handleKeydown.bind(this)}
          />
        </div>
        <div className="button" onClick={this.handleSubmit.bind(this)}>
          提交
        </div>
      </div>
    );
  }
}

export default CommentInput;
